﻿using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Qiniu.Http;
using Qiniu.Storage;
using Qiniu.Util;
using B.S.Database.Write.Api.SysConfig;
using B.S.Database.ErrorCode;
using B.S.Database.Write.Api.Application.Commands.Image;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;

namespace B.S.Database.Write.Api.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ImageController : ControllerBase
    {
        private readonly IMediator mediator;
        private readonly ILogger<ImageController> logger;
        private readonly IConfiguration sysConfig;

        public ImageController(IMediator mediator, ILogger<ImageController> logger, IConfiguration configuration)
        {
            this.mediator = mediator;
            this.logger = logger;
            this.sysConfig = configuration;
        }

        /// <summary>
        /// 上传图片到七牛云OSS
        /// </summary>
        /// <param name="file">图片文件</param>
        /// <returns></returns>
        [HttpPost("uploadToQiniu")]
        [ProducesResponseType(200)]
        [ProducesResponseType(400)]
        public async Task<ActionResult> UploadToQiniuOss(IFormFile file)
        {
            if (file == null || file.Length == 0)
            {
                return BadRequest(new { success = false, message = "请选择图片文件" });
            }

            // 检测文件类型
            string contentType = file.ContentType?.ToLower() ?? "";
            if (!contentType.StartsWith("image/"))
            {
                return BadRequest(new { success = false, message = "只允许上传图片文件" });
            }

            try
            {
                // 获取七牛云配置
                var accessKey = sysConfig["qiniuyunOSS:AccessKey"];
                var secretKey = sysConfig["qiniuyunOSS:SecretKey"];
                var bucket = sysConfig["qiniuyunOSS:Bucket"];
                var baseUrl = sysConfig["qiniuyunOSS:BaseUrl"];

                if (string.IsNullOrEmpty(accessKey) || string.IsNullOrEmpty(secretKey) || string.IsNullOrEmpty(bucket))
                {
                    return BadRequest(new { success = false, message = "七牛云配置不完整" });
                }

                // 生成文件名和路径
                string fileExtension = Path.GetExtension(file.FileName).ToLowerInvariant();
                string fileName = $"{Guid.NewGuid():N}{fileExtension}";
                string dateFolder = DateTime.Now.ToString("yyyy/MM/dd");
                string saveKey = $"Pic/{dateFolder}/{fileName}";

                // 七牛云上传逻辑
                var mac = new Mac(accessKey, secretKey);
                var putPolicy = new PutPolicy { Scope = bucket };
                putPolicy.SetExpires(3600);
                // 不设置 ReturnBody，使用默认返回
                string token = Auth.CreateUploadToken(mac, putPolicy.ToJsonString());
                var qnConfig = new Config { Zone = Zone.ZONE_CN_North };
                var formUploader = new FormUploader(qnConfig);

                using (var ms = new MemoryStream())
                {
                    await file.CopyToAsync(ms);
                    var result = formUploader.UploadData(ms.ToArray(), saveKey, token, null);

                    if (result.Code == 200)
                    {
                        string fileUrl = $"{baseUrl.TrimEnd('/')}/{saveKey}";
                        logger.LogInformation($"七牛云上传成功: {fileUrl}");
                        // 生成带访问令牌的查看链接
                        var viewUrl = GenerateQiniuDownloadToken(accessKey, secretKey, fileUrl, 3600); // 1小时有效期

                        return Ok(new
                        {
                            success = true,
                            message = "上传七牛云OSS成功",
                            data = new
                            {
                                ImageUrl = fileUrl,
                                ViewUrl = viewUrl, // 带访问令牌的查看链接
                                RelativePath = saveKey,
                                FileName = fileName,
                                FileSize = file.Length,
                                Token = token 
                            }
                        });
                    }
                    else
                    {
                        logger.LogError($"七牛云上传失败: Code={result.Code}, Text={result.Text}");
                        return BadRequest(new { success = false, message = $"七牛云上传失败: {result.Text}" });
                    }
                }
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "七牛云上传异常");
                return BadRequest(new { success = false, message = $"上传异常: {ex.Message}" });
            }
        }

        /// <summary>
        /// 上传多张图片到七牛云OSS
        /// </summary>
        /// <param name="files">图片文件集合</param>
        /// <returns></returns>
        [HttpPost("uploadMultipleToQiniu")]
        public async Task<ActionResult> UploadMultipleImagesToQiniuOss([FromForm] IFormFileCollection files)
        {
            if (files == null || files.Count == 0)
            {
                return BadRequest(new { success = false, message = "请选择图片文件" });
            }

            var results = new List<object>();
            var successCount = 0;
            var failCount = 0;

            foreach (var file in files)
            {
                if (file == null || file.Length == 0)
                {
                    results.Add(new { fileName = file?.FileName ?? "未知文件", success = false, message = "文件为空" });
                    failCount++;
                    continue;
                }

                // 检测文件类型
                string contentType = file.ContentType?.ToLower() ?? "";
                if (!contentType.StartsWith("image/"))
                {
                    results.Add(new { fileName = file.FileName, success = false, message = "只允许上传图片文件" });
                    failCount++;
                    continue;
                }

                try
                {
                    // 获取七牛云配置
                    var accessKey = sysConfig["qiniuyunOSS:AccessKey"];
                    var secretKey = sysConfig["qiniuyunOSS:SecretKey"];
                    var bucket = sysConfig["qiniuyunOSS:Bucket"];
                    var baseUrl = sysConfig["qiniuyunOSS:BaseUrl"];

                    if (string.IsNullOrEmpty(accessKey) || string.IsNullOrEmpty(secretKey) || string.IsNullOrEmpty(bucket))
                    {
                        results.Add(new { fileName = file.FileName, success = false, message = "七牛云配置不完整" });
                        failCount++;
                        continue;
                    }

                    // 生成文件名和路径
                    string fileExtension = Path.GetExtension(file.FileName).ToLowerInvariant();
                    string fileName = $"{Guid.NewGuid():N}{fileExtension}";
                    string dateFolder = DateTime.Now.ToString("yyyy/MM/dd");
                    string saveKey = $"Pic/{dateFolder}/{fileName}";

                    // 七牛云上传逻辑
                    var mac = new Mac(accessKey, secretKey);
                    var putPolicy = new PutPolicy { Scope = bucket };
                    putPolicy.SetExpires(3600);
                    // 不设置 ReturnBody，使用默认返回
                    string token = Auth.CreateUploadToken(mac, putPolicy.ToJsonString());
                    var qnConfig = new Config { Zone = Zone.ZONE_CN_North };
                    var formUploader = new FormUploader(qnConfig);

                    using (var ms = new MemoryStream())
                    {
                        await file.CopyToAsync(ms);
                        var result = formUploader.UploadData(ms.ToArray(), saveKey, token, null);

                        if (result.Code == 200)
                        {
                            string fileUrl = $"{baseUrl.TrimEnd('/')}/{saveKey}";
                            logger.LogInformation($"七牛云多图上传成功: {fileUrl}");
                            // 生成带访问令牌的查看链接
                            var viewUrl = GenerateQiniuDownloadToken(accessKey, secretKey, fileUrl, 3600); // 1小时有效期
                            results.Add(new
                            {
                                fileName = file.FileName,
                                success = true,
                                message = "上传成功",
                                data = new
                                {
                                    ImageUrl = fileUrl,
                                    ViewUrl = viewUrl, // 用于查看的链接
                                    RelativePath = saveKey,
                                    FileName = fileName,
                                    FileSize = file.Length,
                                    Token = token
                                }
                            });
                            successCount++;
                        }
                        else
                        {
                            logger.LogError($"七牛云多图上传失败: Code={result.Code}, Text={result.Text}");
                            results.Add(new { fileName = file.FileName, success = false, message = $"上传失败: {result.Text}" });
                            failCount++;
                        }
                    }
                }
                catch (Exception ex)
                {
                    logger.LogError(ex, $"七牛云多图上传异常: {file.FileName}");
                    results.Add(new { fileName = file.FileName, success = false, message = $"上传异常: {ex.Message}" });
                    failCount++;
                }
            }

            return Ok(new
            {
                success = true,
                message = $"批量上传完成，成功: {successCount} 个，失败: {failCount} 个",
                data = new
                {
                    TotalCount = files.Count,
                    SuccessCount = successCount,
                    FailCount = failCount,
                    Results = results
                }
            });
        }

        /// <summary>
        /// 图片添加
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost("create")]
        public Task<Apiresult<object>> PictureCreate(PictureCreateCommands request)
        {
            return mediator.Send(request);
        }

        /// <summary>
        /// 统一图片上传并保存到数据库
        /// </summary>
        /// <param name="request">包含图片文件和溯源ID的请求</param>
        /// <returns></returns>
        [HttpPost("upload-and-save")]
        [ProducesResponseType(200)]
        [ProducesResponseType(400)]
        public async Task<Apiresult<object>> UploadAndSavePicture([FromForm] PictureUploadAndCreateCommands request)
        {
            return await mediator.Send(request);
        }

        /// <summary>
        /// 单文件图片上传并保存
        /// </summary>
        /// <param name="file">图片文件</param>
        /// <param name="traceabilityId">溯源ID</param>
        /// <param name="imageType">图片类型</param>
        /// <param name="isAppend">是否追加模式</param>
        /// <returns></returns>
        [HttpPost("upload-single")]
        [ProducesResponseType(200)]
        [ProducesResponseType(400)]
        public async Task<Apiresult<object>> UploadSinglePicture(
            IFormFile file,
            [FromForm] int traceabilityId,
            [FromForm] string imageType = "Inspection_Repor",
            [FromForm] bool isAppend = true)
        {
            var request = new PictureUploadAndCreateCommands
            {
                File = file,
                TraceabilityId = traceabilityId,
                ImageType = imageType,
                IsAppend = isAppend
            };
            return await mediator.Send(request);
        }

        /// <summary>
        /// 多文件图片上传并保存
        /// </summary>
        /// <param name="files">图片文件集合</param>
        /// <param name="traceabilityId">溯源ID</param>
        /// <param name="imageType">图片类型</param>
        /// <param name="isAppend">是否追加模式</param>
        /// <returns></returns>
        [HttpPost("upload-multiple")]
        [ProducesResponseType(200)]
        [ProducesResponseType(400)]
        public async Task<Apiresult<object>> UploadMultiplePictures(
            IFormFileCollection files,
            [FromForm] int traceabilityId,
            [FromForm] string imageType = "Inspection_Repor",
            [FromForm] bool isAppend = true)
        {
            var request = new PictureUploadAndCreateCommands
            {
                Files = files,
                TraceabilityId = traceabilityId,
                ImageType = imageType,
                IsAppend = isAppend
            };
            return await mediator.Send(request);
        }

        /// <summary>
        /// 生成带访问令牌的文件查看链接
        /// </summary>
        /// <param name="fileName">文件名</param>
        /// <param name="folder">文件夹路径（可选）</param>
        /// <param name="expires">过期时间（秒，默认3600）</param>
        /// <returns></returns>
        [HttpGet("generateSecureFileLink")]
        public ActionResult GenerateSecureFileLink([FromQuery] string fileName, [FromQuery] string folder = "", [FromQuery] int expires = 3600)
        {
            if (string.IsNullOrWhiteSpace(fileName))
            {
                return BadRequest(new { success = false, message = "请输入文件名" });
            }

            try
            {
                var baseUrl = sysConfig["qiniuyunOSS:BaseUrl"];
                var accessKey = sysConfig["qiniuyunOSS:AccessKey"];
                var secretKey = sysConfig["qiniuyunOSS:SecretKey"];

                if (string.IsNullOrEmpty(baseUrl) || string.IsNullOrEmpty(accessKey) || string.IsNullOrEmpty(secretKey))
                {
                    return BadRequest(new { success = false, message = "七牛云配置不完整" });
                }

                // 构建文件路径
                string filePath = string.IsNullOrEmpty(folder) ? fileName : $"{folder.TrimEnd('/')}/{fileName}";
                string fileUrl = $"{baseUrl.TrimEnd('/')}/{filePath}";

                // 生成带访问令牌的链接
                var secureUrl = GenerateQiniuDownloadToken(accessKey, secretKey, fileUrl, expires);

                return Ok(new
                {
                    success = true,
                    message = "安全文件链接生成成功",
                    data = new
                    {
                        FileName = fileName,
                        Folder = folder,
                        FilePath = filePath,
                        OriginalUrl = fileUrl,
                        SecureUrl = secureUrl,
                        ExpiresIn = expires,
                        ExpiresAt = DateTime.Now.AddSeconds(expires).ToString("yyyy-MM-dd HH:mm:ss"),
                        GenerateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
                    }
                });
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "生成安全文件链接异常");
                return BadRequest(new { success = false, message = $"生成链接异常: {ex.Message}" });
            }
        }

        /// <summary>
        /// 生成七牛云访问令牌（简化版本）
        /// </summary>
        /// <param name="accessKey">AccessKey</param>
        /// <param name="secretKey">SecretKey</param>
        /// <param name="url">文件URL</param>
        /// <param name="expires">过期时间（秒）</param>
        /// <returns></returns>
        private string GenerateQiniuDownloadToken(string accessKey, string secretKey, string url, int expires)
        {
            try
            {
                // 简化版本：直接返回原始URL
                // 建议将七牛云存储空间设置为公开空间
                logger.LogInformation("使用简化版本的访问令牌生成，建议将存储空间设置为公开空间");
                return url;
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "生成七牛云访问令牌异常");
                return url; // 如果生成失败，返回原始URL
            }
        }
        /// <summary>
        /// 图片删除
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost("delete")]
        public Task<Apiresult<object>> PictrueDelete(PictrueUpdateCommands request)
        {
            return mediator.Send(request);
        }

        /// <summary>
        /// 删除指定图片
        /// </summary>
        /// <param name="request">删除请求</param>
        /// <returns></returns>
        [HttpPost("delete-picture")]
        [ProducesResponseType(200)]
        [ProducesResponseType(400)]
        public async Task<Apiresult<object>> DeletePicture(PictureDeleteCommands request)
        {
            return await mediator.Send(request);
        }

        /// <summary>
        /// 删除指定字段的所有图片
        /// </summary>
        /// <param name="traceabilityId">溯源ID</param>
        /// <param name="imageType">图片类型</param>
        /// <param name="deleteFromQiniu">是否删除七牛云文件</param>
        /// <returns></returns>
        [HttpPost("delete-all-pictures")]
        [ProducesResponseType(200)]
        [ProducesResponseType(400)]
        public async Task<Apiresult<object>> DeleteAllPictures(
            [FromForm] int traceabilityId,
            [FromForm] string imageType,
            [FromForm] bool deleteFromQiniu = true)
        {
            var request = new PictureDeleteCommands
            {
                TraceabilityId = traceabilityId,
                ImageType = imageType,
                DeleteFromQiniu = deleteFromQiniu
            };
            return await mediator.Send(request);
        }

        /// <summary>
        /// 删除指定图片URL
        /// </summary>
        /// <param name="traceabilityId">溯源ID</param>
        /// <param name="imageType">图片类型</param>
        /// <param name="imageUrl">要删除的图片URL</param>
        /// <param name="deleteFromQiniu">是否删除七牛云文件</param>
        /// <returns></returns>
        [HttpPost("delete-specific-picture")]
        [ProducesResponseType(200)]
        [ProducesResponseType(400)]
        public async Task<Apiresult<object>> DeleteSpecificPicture(
            [FromForm] int traceabilityId,
            [FromForm] string imageType,
            [FromForm] string imageUrl,
            [FromForm] bool deleteFromQiniu = true)
        {
            var request = new PictureDeleteCommands
            {
                TraceabilityId = traceabilityId,
                ImageType = imageType,
                ImageUrl = imageUrl,
                DeleteFromQiniu = deleteFromQiniu
            };
            return await mediator.Send(request);
        }

        /// <summary>
        /// 删除指定索引的图片
        /// </summary>
        /// <param name="traceabilityId">溯源ID</param>
        /// <param name="imageType">图片类型</param>
        /// <param name="imageIndex">要删除的图片索引（从0开始）</param>
        /// <param name="deleteFromQiniu">是否删除七牛云文件</param>
        /// <returns></returns>
        [HttpPost("delete-picture-by-index")]
        [ProducesResponseType(200)]
        [ProducesResponseType(400)]
        public async Task<Apiresult<object>> DeletePictureByIndex(
            [FromForm] int traceabilityId,
            [FromForm] string imageType,
            [FromForm] int imageIndex,
            [FromForm] bool deleteFromQiniu = true)
        {
            var request = new PictureDeleteCommands
            {
                TraceabilityId = traceabilityId,
                ImageType = imageType,
                ImageIndex = imageIndex,
                DeleteFromQiniu = deleteFromQiniu
            };
            return await mediator.Send(request);
        }

        /// <summary>
        /// 获取指定字段的图片列表
        /// </summary>
        /// <param name="traceabilityId">溯源ID</param>
        /// <param name="imageType">图片类型</param>
        /// <returns></returns>
        [HttpGet("get-picture-list")]
        [ProducesResponseType(200)]
        [ProducesResponseType(400)]
        public async Task<Apiresult<object>> GetPictureList(
            [FromQuery] int traceabilityId,
            [FromQuery] string imageType)
        {
            var request = new PictureListCommands
            {
                TraceabilityId = traceabilityId,
                ImageType = imageType
            };
            return await mediator.Send(request);
        }
        /// <summary>
        /// 图片删除2
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost("delete2")]
        public Task<Apiresult<object>> PictrueDelete2(PictrueUpdatetwoCommands request)
        {
            return mediator.Send(request);
        }
        /// <summary>
        /// 图片删除3
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost("delete3")]
        public Task<Apiresult<object>> PictrueDelete3(PictrueUpdatethreeCommands request)
        {
            return mediator.Send(request);
        }
    }
}
